import decimal
from django.db import transaction
from rest_framework import serializers
from .models import Order, OrderDetail
from goods.models import Good
from preDepositLogs.models import PreDepositLog
from goods.serializers import GoodSuperSerializer
# from users.signals import user_signal
from django.contrib.auth import get_user_model
UserModel = get_user_model()


class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = '__all__'


class GoodSerializer(serializers.ModelSerializer):

    class Meta:
        model = Good
        fields = ('id', 'name')

    def create(self, validated_data):
        pass


class OrderDetailSerializer(serializers.ModelSerializer):
    # order = OrderSerializer(required=False)
    # good = serializers.PrimaryKeyRelatedField(read_only=True)
    # good = serializers.RelatedField(queryset=Good.objects.all())
    # num = serializers.IntegerField()
    # totalActualCharge = serializers.DecimalField(max_digits=19, decimal_places=2)

    class Meta:
        model = OrderDetail
        fields = ('good', 'num', 'totalActualCharge')


class UserSuperSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserModel
        fields = ('name', 'id')


class PostOrderSuperSerializer(serializers.ModelSerializer):
    user = UserSuperSerializer
    orderDetail = OrderDetailSerializer(many=True)
    type = serializers.ChoiceField(default=1, choices=((1, '预存款'), (2, '积分'), (0, '赠送')))

    class Meta:
        model = Order
        fields = ('user', 'records', 'note', 'orderDetail', 'type')

    def create(self, validated_data):
        with transaction.atomic():

            print('serializers')
            order_id = Order.objects.create_order_num()
            validated_data.setdefault('orderId', order_id)
            user = validated_data['user']
            i_type = int(validated_data['type'])

            order_detail = validated_data['orderDetail']
            total_money = decimal.Decimal(0.00)
            total_actual_charge = decimal.Decimal(0.00)
            total_integral = 0
            total_discount_money = decimal.Decimal(0.00)
            dics = []
            for detail in order_detail:
                _good = detail['good']
                discount = decimal.Decimal(0.00)
                if _good.isDiscount == 1:
                    discount = _good.discount
                    if user.discount < 1:
                        discount = user.discount
                else:
                    discount = 1

                money = decimal.Decimal(detail['num']) * _good.price
                discount_money = money * discount
                integral = _good.integral * detail['num']
                actual_charge = detail['totalActualCharge']
                _discount = actual_charge / money
                total_money += money
                total_discount_money += discount_money
                total_actual_charge += actual_charge
                total_integral += integral
                dic = {'price': _good.price, 'discount': _discount, 'money': money, 'detail': detail,
                       'i_type': validated_data['type'], 'total_integral': integral,
                       'total_discount_money': discount_money}
                # dic.update(detail)
                dics.append(dic)

            if i_type == 1:
                if user.preDeposit < total_actual_charge:
                    raise serializers.ValidationError('账户余额不足')
            elif i_type == 2:
                if user.integral < total_integral:
                    raise serializers.ValidationError('积分余额不足')

            order = Order.objects.create_order(**validated_data)

            # user_signal.send(sender=order.__class__, v1=user, v2="1")
            for t in dics:
                OrderDetail.objects.create_order_detail(order, t['price'], t['discount'], t['money'], t['i_type'],
                                                        t['total_integral'], t['total_discount_money'], **t['detail'])

            if i_type in [1, 0]:
                order.totalActualCharge = total_actual_charge
                order.totalDiscountMoney = total_discount_money
                order.totalMoney = total_money
                order.discount = total_actual_charge / total_money
                order.save(update_fields=['totalActualCharge', 'totalMoney', 'discount', 'totalDiscountMoney'])
                if i_type == 1:
                    PreDepositLog.objects.create(**{'operationMoney': -order.totalActualCharge, 'operationType': 1,
                                                    'user': user})
            elif i_type == 2:
                order.total_integral = total_integral
                order.save(update_fields=['total_integral'])
                PreDepositLog.objects.create_integral(**{'operationMoney': -order.total_integral, 'user': user})

            return order


class GetOrderSuperSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = '__all__'


class GetOrderAllowSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = '__all__'

    def create(self, validated_data):
        pass


class OrderDetailListSerializer(serializers.ModelSerializer):
    good = GoodSerializer()

    class Meta:
        model = OrderDetail
        fields = '__all__'


class OrderListSerializer(serializers.ModelSerializer):
    user = UserSuperSerializer()
    # orderDetail = serializers.PrimaryKeyRelatedField(many=True, source='orderDetail')
    orderDetail = OrderDetailListSerializer(many=True)

    class Meta:
        model = Order
        fields = ('id', 'orderId', 'user', 'totalMoney', 'totalDiscountMoney', 'totalActualCharge', 'note', 'type',
                  'total_integral', 'state', 'orderDetail', 'createdAt', 'discount')


